import { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Button } from '@kernelproxy/ui';
import { useLanguage, useLocalizedLink } from '@kernelproxy/i18n';
import { authService } from '../services/auth';
import { useToast } from '../contexts/ToastContext';

const ResetPassword = () => {
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { language } = useLanguage();
  const { getLink } = useLocalizedLink();
  const toast = useToast();

  const userId = searchParams.get('userId');
  const secret = searchParams.get('secret');

  useEffect(() => {
    if (!userId || !secret) {
      setError(language === 'zh-CN' ? '无效的重置链接' : 'Invalid reset link');
    }
  }, [userId, secret, language]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (password !== confirmPassword) {
      setError(language === 'zh-CN' ? '密码不匹配' : 'Passwords do not match');
      return;
    }

    if (password.length < 8) {
      setError(language === 'zh-CN' ? '密码至少需要8个字符' : 'Password must be at least 8 characters');
      return;
    }

    if (!userId || !secret) {
      setError(language === 'zh-CN' ? '无效的重置链接' : 'Invalid reset link');
      return;
    }

    setLoading(true);

    try {
      const result = await authService.confirmPasswordRecovery(userId, secret, password);
      if (result.success) {
        // Password reset successful, redirect to login
        toast.success(language === 'zh-CN' ? '密码重置成功！请使用新密码登录' : 'Password reset successfully! Please login with your new password');
        navigate(getLink('/login?reset=success'));
      } else {
        const errorMsg = language === 'zh-CN' ? '重置密码失败，链接可能已过期' : 'Failed to reset password, link may have expired';
        setError(errorMsg);
        toast.error(errorMsg);
      }
    } catch (err) {
      const errorMsg = language === 'zh-CN' ? '重置密码失败，请重试' : 'Failed to reset password, please try again';
      setError(errorMsg);
      toast.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4 sm:px-6 lg:px-8 transition-colors duration-300">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <a href="https://kernelproxy.com" className="inline-flex items-center justify-center">
            <span className="text-3xl font-bold text-[#00d4ff]">kernel</span>
            <span className="text-3xl font-bold text-[#0f1c3f] dark:text-white">Proxy</span>
          </a>
          <h2 className="mt-6 text-3xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '设置新密码' : 'Set New Password'}
          </h2>
        </div>

        <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow-lg sm:rounded-lg sm:px-10 transition-colors duration-300">
          {error && (
            <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
              <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            </div>
          )}

          <form className="space-y-6" onSubmit={handleSubmit}>
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                {language === 'zh-CN' ? '新密码' : 'New Password'}
              </label>
              <div className="mt-1">
                <input
                  id="password"
                  name="password"
                  type="password"
                  autoComplete="new-password"
                  required
                  value={password}
                  onChange={e => setPassword(e.target.value)}
                  className="appearance-none block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300"
                />
              </div>
            </div>

            <div>
              <label htmlFor="confirm-password" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                {language === 'zh-CN' ? '确认新密码' : 'Confirm New Password'}
              </label>
              <div className="mt-1">
                <input
                  id="confirm-password"
                  name="confirm-password"
                  type="password"
                  autoComplete="new-password"
                  required
                  value={confirmPassword}
                  onChange={e => setConfirmPassword(e.target.value)}
                  className="appearance-none block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300"
                />
              </div>
            </div>

            <div>
              <Button type="submit" fullWidth variant="gradient" disabled={loading}>
                {loading 
                  ? (language === 'zh-CN' ? '重置中...' : 'Resetting...') 
                  : (language === 'zh-CN' ? '重置密码' : 'Reset Password')}
              </Button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ResetPassword;
